package com.regentsoft.cloudback.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * Created by work on 2017/11/27.
 *
 * @author lumr
 */
@Component
public class RedisClient {
    private final ShardedJedisPool pool;

    @Autowired
    public RedisClient(ShardedJedisPool pool) {
        this.pool = pool;
    }

    public String get(String key){
        try(ShardedJedis shardedJedis = pool.getResource()){
            return shardedJedis.get(key);
        }
    }

    public <T> T get(String key,Class<T> tClass){
        String jsonStr = this.get(key);
        return JsonUtil.toObject(jsonStr,tClass);
    }

    public String set(String key,String value){
        try(ShardedJedis shardedJedis = pool.getResource()){
            return shardedJedis.set(key,value);
        }
    }

    public String set(String key,int seconds,String value){
        try(ShardedJedis shardedJedis = pool.getResource()){
            return shardedJedis.setex(key,seconds,value);
        }
    }

    public String set(String key,Object obj){
        String value = JsonUtil.toJsonStr(obj);
        return this.set(key,value);
    }

    public String set(String key,int seconds,Object obj){
        String value = JsonUtil.toJsonStr(obj);
        return this.set(key,seconds,value);
    }


    public boolean exists(String key){
        try(ShardedJedis shardedJedis = pool.getResource()){
            return shardedJedis.exists(key);
        }
    }

    public long expire(String key,int seconds){
        try(ShardedJedis shardedJedis = pool.getResource()){
            return shardedJedis.expire(key,seconds);
        }
    }
}
